Authentication API
Security is all about two things: authorization and authentication. Authentication is the process of validating that users are who they say they are based on credentials that they supply in the form of unique usernames and password combinations. Authorization is the process of validating that authenticated users have the required permissions to perform some action, whether it's viewing pages in a directory, executing a specific piece of code, or viewing a particular piece of text. Authorization is typically implemented by assigning a role—or several roles—to users when they are authenticated and then by using conditional logic to restrict or allow the display of text or execution of code based on those role(s).
Authentication and authorization are used together in web applications to secure applications or parts of applications and to personalize and restrict content on those pages. ColdFusion MX introduced several new tags and functions that developers use to authenticate and authorize tasks in applications. These tags and functions take advantage of the Java Authentication and Authorization (JAAS) framework, a J2EE security framework built into the underlying J2EE application server on top of which ColdFusion MX is deployed. The tags and functions that allow developers to take advantage of JAAS include <CFLOGIN>, <CFLOGINUSER>, <CFLOGOUT>, isUserInRole(), and getAuthUser().
Before the release of ColdFusion MX it was not uncommon for developers to write their own application-specific security module using the session scope and conditional logic. The fact that the security framework is now pre-existent is one compelling reason to use it, but there are other reasons to take advantage of the application server's JAAS framework as well. One reason to use JAAS is that it allows ColdFusion and other Java/J2EE applications to talk to each other. This means a user authenticated in one of these environments is also seen as authenticated in the other. It permits more flexibility in your applications and ensures that in a ColdFusion/Java environment, single sign-on is easily attained. Another very compelling reason to use JAAS is the fact that user authentication information implements the Java Serializable class. This means that in a cluster of servers, a user authenticated on one server (instance) is also authenticated on all other servers in the cluster.
You may be wondering why there is a need for this API if CFML now has built-in language constructs for implementing security. The short answer is that you don't need it. The Authentication API doesn't do anything but give developers an easy-to-use interface to the security tags and functions built into CFML. That's the point of any API: to make other resources easier to use by wrapping them in an easy-to-use interface. You can use this API in conjunction with code already written with the CFML security tags without having to rewrite any code. The API offers a single custom tag interface so you can restrict access to code to a specific role or roles; specify a list of roles that a user may be a member of in order to execute code; redirect users or include code based on authorization failure; log users in and out; and specify alternative text to display when a user is not authorized. In addition, database examples are included to illustrate what a typical security database table structure might look like, and a ColdFusion component (CFC) is supplied that talks to the database. The Authentication API illustrates one possible way to organize code that requires database interaction, business logic, and integration/interaction with the display layer of a ColdFusion application.
Ignoring the sample code and database scripts/examples, the Authentication API code consists of a CFC and a custom tag. The CFC contains methods for authenticating a user based on the username and password stored in the database ("user" table) and retrieving a user's roles. (Roles are stored in the role table and the user/role relationship is stored in the "userrole" table.) The majority of the API code is found within the secure.cfm custom tag. This is because the majority of the code that is typically written to authenticate and authorize users has to do with authorization (permissions) checks in the display and business logic (controller if you are used to MVC terminology) layers of an application.
Why a custom tag? They offer developers an interface that is easy to implement in the display tier of applications. Although CFCs are generally considered the best location for business logic, security is an exception to this rule. Security requires state management and also frequently interacts with the display tier. ColdFusion component calls are not ideal for this type of heavy user interface interaction, nor should they be aware of state. For these primary reasons, the calls to the ColdFusion security framework are housed within a custom tag and a CFC is used to authenticate (but not authorize) users. The code within the CFC methods can be easily changed to suit the user/role lookup logic in your application(s) without having to modify the tag.
Installing the Authentication API
In order to install and use the Authentication API:
- Copy the code into a web-accessible directory.
- To use the sample application, create a datasource called mmsecurity in the ColdFusion administrator that either connects with the included Microsoft Access database or to a SQL Server database created by attaching the included MDF file or running the included SQL script. If you use the SQL script to create new database tables, you will have to add the "admin" and "guest" users ("user" table) described in Step 4 below, add an "admin" and a "guest" role ("role" table), and associate the users with their roles ("userrole" table).
- Open Application.cfm in the samples directory, making sure that the following variables in the <cfscript> block have the proper values: request.dsn, request.relativePath, and request.cfcPath. If you created the mmsecurity datasource and the path from the web root to the samples directory is macromedia\wwwroot\samples, then you should not have to change any of these values.
- Browse to the installed samples subdirectory directory. The database should have two users already in it: admin and guest (password is the same as the username).
- Click the links to see different behavior in action, taking a look at the code in the pages being browsed.
Installation notes:
- In a production environment where several applications might use the API, you can place the custom tag and ColdFusion component in a central location.
- Although it is not required, consider enabling J2EE session variables in the ColdFusion Administrator
- In a production environment, cache global variables in the application scope.
Using the Authentication API
In order to use the Authentication API, the CFC called security.cfc has to be in an accessible location, as does the security.cfm custom tag. Table 1 shows the attributes of the security.cfm custom tag.
| Attribute | Description |
|---|---|
| objSecurity | Instance of the security.cfm CFC (included with the application) |
| Loginform | Path to the login form: if redirect is "true", its value is used in a <CFLOCATION>, otherwise it is used in a <CFINCLUDE> |
| Redirect | Boolean value specifying whether or not to redirect to the login form |
| Username | Username to authenticate |
| Password | Password to authenticate |
| Role | Role(s) to validate; used in a <CFLOGINUSER> |
| Alttext | Alt text to show when a user is not within a role |
| Defaultrole | Role that users are in by default ("anonymous") |
| Logout | Boolean value specifying whether or not to log the current user out |
| OnSuccess | Location to redirect a user to upon successful login; if blank, no redirect happens and the user browses to whatever page they are requesting |
| AnyRole | List of roles a user can be a member of in order to be authorized—not a mutually exclusive list |
| retVal | Tag returning a local variable to the caller page with the name of this value when performing role authorization; the value is Boolean, indicating authorization ("true") or failed authorization ("false"); default value is "authorized" |
Here is how the security.cfm custom tag attributes work. The tag always requires an instance of the CFC to be passed (the "objSecurity" attribute), and you can create and persist this instance in the application scope. No other attributes are always required; it depends on what you are trying to do with the tag.
If "username" and "password" are passed to the tag, the current user is immediately logged out and the tag attempts to log the user in using the passed credentials.
If a user is not currently logged in and the "defaultrole" attribute is passed with a value, the user is automatically logged in as "anonymous" and is in the role(s) passed to the tag as the value of the "defaultrole" attribute. This is useful when users are supposed to be seen as logged-in by default.
If the "role" attribute is passed, the tag validates that the user is in that role. If a list of roles is passed, the tag validates that they're in all of those roles. The following happens if the user fails this validation:
- The user is redirected if the "redirect" attribute is "true" and the "loginform" attribute has a value. The value of the "loginform" attribute specifies the redirect URL (<CFLOCATION>).
- The user is not redirected and a file is included if the "redirect" attribute is "false" and the "loginform" attribute has a value. The tag includes the value of the "loginform" attribute (using <CFINCLUDE>).
- If the "alttext" attribute has a value, this value is displayed if the user was not redirected and no form was included.
- The tag sets a variable in the local "variables" scope of the page that called it; the value of the variable is "false." The name of the variable is determined by the value of the "retVal" attribute if it was passed; otherwise the name of the variable is "authorized." This allows the code in the local page to run code conditionally after the tag call, based on whether or not the user was validated as being a member of any required role(s).
The "anyRole" attribute behaves exactly as the "role" attribute, except that the user need only be in one of the roles listed in its value. This is useful when a user only has to be in one of several possible roles. The "anyRole" attribute and "role" attribute can be combined so that a user must be in roles A, B, and C (all passed to the tag in a list using the "role" attribute) and must be in at least one of the following roles: D, E, or F (passed as a list to the "anyRole" attribute).
In addition to securing entire pages or directories, you may wrap the tag around text so it appears only to members of a certain role or roles.
You can nest tags in order to control text further within text that is already secure. The tag does not execute any nested code if the current user is not in the required role(s). For this reason, if calls to the tag are nested within other calls to the tag, the user must be in the role(s) specified by the outer tag calls.
Passing the "logout" attribute with the value "true" logs out the current user.
Note: The included database schema has a concept of users and roles. If an application is going to have many users with shared responsibilities, it is recommended that a "groups" table be created and users be put into groups. To do this, create a "groups" table to hold one row for each possible group and a "usergroup" table that contains the userID (FK) and GroupID (FK) for each group that each user is in. Apply roles to groups rather than users by adding a "grouprole" table and modifying the CFC to retrieve all roles for a user's group(s).
Note: If you prefer to use the custom tag with CFC methods other than those that come with the API ColdFusion component, the object instance you pass to the tag as the value of its "objSecurity" attribute must have the methods listed in Table 2 publicly available.
| Method Name | Arguments | Description | Return Type |
|---|---|---|---|
| init | DSN (string) | Sets the DSN for object | Void |
| getUserID | username (string) password (string) |
Gets unique (numeric) userID for user | Numeric |
| getRole | UserID (numeric) | Gets the roles for user | string (list) |